<?php
namespace app\controller;

use app\BaseController;
use app\model\User;

/**
 * 登录
 * Class Login
 * @package app\controller
 * @author 下雨吧จุ๊บ
 */
class Login
{

    /**
     * @apiGroup 登录
     * @apiVersion 1.0.0
     * @api {POST} /login  登录
     * @apiDescription 登录选项
     * @apiParam {String} username 用户名(必填*)
     * @apiParam {String} password 密码(必填*)
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * username: 'xxx',
     * password: 'xxxxx',
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '填写完整参数,一定是参数不完整',
     * }
     */
    public function save($data = '')
    {
        //获取参数
        $data = input();
        //账号密码校验
        if (empty($data['username'])){
            error('请输入账号');
        }
        if (empty($data['password'])){
            error('请输入密码');
        }
        //查看当前用户是否存在
        $info = User::where('username',$data['username'])->find();
        if (empty($info)){
            error('用户不存在');
        }
        //用户存在,验证密码
        if (md5($data['password']) != $info['password']){
            error('密码错误');
        }
        if ($info['id'] == 1){
            $quanxian = jurisdiction();
        }else{
            //获取权限
            $quanxian = User::alias('u')
                ->join(['user_character'=>'uc'],'u.id=uc.userid')
                ->join(['character'=>'c'],'c.id=uc.characterid')
                ->join(['character_jurisdiction'=>'cj'],'c.id=cj.characterid')
                ->join(['jurisdiction'=>'j'],'j.id=cj.jurisdictionid')
                ->where('u.id',$info['id'])
                ->field('j.id,j.pid,j.title')
                ->select()
                ->toarray();
            if (!empty($quanxian)){
                $quanxian = array_unique_fb($quanxian,array('id','pid','title'));
            }
        }
        $info['jurisdiction'] = $quanxian;
        //验证通过,登录成功,储存toke
        $_SESSION['token']['value'] = $info['token'];
        $_SESSION['token']['time'] = time();
        //储存用户信息
        cache($info['token'], $info, 3600);
        saveLog($data['username'].'----'.$data['password'].'----登录成功');
        success(array(),'登录成功');
    }

    /**
     * @apiGroup 登录
     * @apiVersion 1.0.0
     * @api {GET} /login  退出登录
     * @apiDescription 退出登录
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '退出成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示',
     * }
     */
    public function index()
    {
        $_SESSION['token']['time'] = '';
        success(array(),'退出成功');
    }
}
